import re

from django.contrib.auth import login
from django.shortcuts import render,redirect
# Create your views here.
from django.urls import reverse
from django.views import View
from django.http import HttpResponseBadRequest,JsonResponse

from apps.users.models import User


class RegisterView(View):
    # 如果为get方法则跳转到提供注册表格
    def get(self,request):
        return render(request,'register.html')

    # 如果有参数则收集表格内容
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        # 判断是否符合规则
        if not all([username, password, password2, mobile, allow]):
            return HttpResponseBadRequest('参数不全')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseBadRequest('用户名不符合规则')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseBadRequest('密码不符合规则')
        if password2 != password:
            return HttpResponseBadRequest('密码不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('手机号不正确')
        if allow != 'on':
            return HttpResponseBadRequest('请勾选协议')

        # 保存到数据库库
        user = User.objects.create_user(username=username,password=password,mobile=mobile)

        # 保持登陆状态
        login(request,user)
        return redirect(reverse('contents:index'))


# 检测用户名重复
class RegisterUsernameView(View):
    # 在js进行拼接,使得第三个参数为用户名
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'count':count})

class RegisterMobileView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'count':count})

